import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus';
import { Result, ResultError } from '@/types';


export const getCookies = (key: string) => {
    return Cookies.get(key)
}

export const setStorage = (key: string, value: any, time = 0) => {
    localStorage.setItem(key, JSON.stringify({ data: value, time: time == 0 ? -1 : (new Date().getTime() + time * 1000) }))
}

export const getStorage = (key: string) => {
    let data = localStorage.getItem(key)
    if (!data) return null
    let dataObj = JSON.parse(data)
    if (dataObj.time != -1 && dataObj.time < new Date().getTime()) {
        localStorage.removeItem(key)
        return null
    } else {
        return dataObj.data
    }
}

export const errorMsg = (res: ResultError) => {
    if (res.code == 'SERVER_ERRPR') {
        let message = '';
        ElMessage({
            message: res?.data?.message || '服务器请求错误，请稍后再试',
            grouping: true,
            type: 'error',
        })
    } else if (res.code == 'ERRPR') {
        ElMessage({
            message: res?.data?.message || '未知错误',
            grouping: true,
            type: 'error',
            duration: 1500
        })
    }  else if (res.code == ' ERRPR_AUTH') {
        ElMessage({
            message: res?.data?.message || '未知错误',
            grouping: true,
            type: 'error',
            duration: 1500
        })
    }else if (typeof res == 'string') {
        ElMessage({
            message: res || '处理失败!',
            grouping: true,
            type: 'error',
            duration: 1500
        })
    }
}

export const successMsg = (res: Result | string) => {
    if (typeof res == 'string') {
        ElMessage({
            message: res,
            grouping: true,
            type: 'success',
            duration: 1500
        })
    } else if (typeof res == 'object') {
        ElMessage({
            message: res?.message || '处理成功！',
            grouping: true,
            type: 'success',
            duration: 1500
        })
    }
}

export const getRouteDefault = (routes: any,menus:any) => {
    menus.forEach((item:any) => {
        
    });
}

const copyDomText = (val:string):void => {
    // 获取需要复制的元素以及元素内的文本内容
    const text = val
    // 添加一个input元素放置需要的文本内容
    const input = document.createElement('input')
    input.value = text
    document.body.appendChild(input)
    // 选中并复制文本到剪切板
    input.select()
    document.execCommand('copy')
    // 移除input元素
    document.body.removeChild(input)
    successMsg('复制成功')
  }
export default {
    getCookies,
    setStorage,
    getStorage,
    errorMsg,
    successMsg,
    copyDomText,
    getRouteDefault
}